package org.jeecg.modules.flower.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.*;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecg.modules.flowerutil.PeriodUtils;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.def.TemplateExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flower.vo.FlowerPrePage;
import org.jeecgframework.poi.excel.view.JeecgTemplateExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 销售确认单主表
 * @Author: jeecg-boot
 * @Date: 2022-06-27
 * @Version: V1.0
 */
@Api(tags = "销售确认单主表")
@RestController
@RequestMapping("/flower/flowerPre")
@Slf4j
public class FlowerPreController {
    @Autowired
    private IFlowerPreService flowerPreService;
    @Autowired
    private IFlowerPreinfoService flowerPreinfoService;
    @Autowired
    private IFlowerPreinfoHsService flowerPreinfoHsService;

    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IFlowerStorehouseService flowerStorehouseService;

    @Value("${yth.tempPreExcelOrder}")
    private String tempPreExcelOrder;

    @Value("${yth.tempPreExcelOut}")
    private String tempPreExcelOut;

    @Autowired
    private XsglService xsglService;

    @Autowired
    private IFlowerSettleAccountsService settleAccountsService;

    private static String ADDPRE = "addFlowerPre";

    /**
     * 分页列表查询
     *
     * @param flowerPre
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "销售确认单主表-分页列表查询")
    @ApiOperation(value = "销售确认单主表-分页列表查询", notes = "销售确认单主表-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "flower/FlowerPreList")
    public Result<?> queryPageList(FlowerPre flowerPre,
                                   @RequestParam(name = "isSure", defaultValue = "") String isSure,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(value = "sDate", defaultValue = "") String sDate,
                                   @RequestParam(value = "eDate", defaultValue = "") String eDate,
                                   @RequestParam(value = "sfDate", defaultValue = "") String sfDate,
                                   @RequestParam(value = "efDate", defaultValue = "") String efDate,
                                   HttpServletRequest req) {
//		QueryWrapper<FlowerPre> queryWrapper = QueryGenerator.initQueryWrapper(flowerPre, req.getParameterMap());
        QueryWrapper<FlowerPre> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(flowerPre.getOutorderPreNo())) {
            queryWrapper.like("outorder_pre_no", flowerPre.getOutorderPreNo());
        }
        if (StringUtils.isNotBlank(flowerPre.getSealSureUser())) {
            queryWrapper.eq("seal_sure_user", flowerPre.getSealSureUser());
        }
        if (StringUtils.isNotBlank(flowerPre.getFinaSureUser())) {
            queryWrapper.eq("fina_sure_user", flowerPre.getFinaSureUser());
        }
        if (StringUtils.isNotBlank(isSure)) {
            if ("1".equals(isSure)) {
                queryWrapper.isNotNull("fina_sure_user");
                queryWrapper.ne("fina_sure_user", "");
            } else if ("2".equals(isSure)) {
                queryWrapper.and(wrapper -> wrapper.or().isNull("fina_sure_user").or().eq("fina_sure_user", ""));
            }
        }
        if (StringUtils.isNotBlank(flowerPre.getNo())) {
            queryWrapper.like("no", flowerPre.getNo());
        }
        if (flowerPre.getState() != null) {
            queryWrapper.eq("state", flowerPre.getState());
        }
        if (StringUtils.isNotBlank(sDate)) {
            queryWrapper.ge("seal_sure_time", sDate);
        }
        if (StringUtils.isNotBlank(eDate)) {
            queryWrapper.le("seal_sure_time", eDate + " 23:59:59");
        }
        if (StringUtils.isNotBlank(sfDate)) {
            queryWrapper.ge("fina_sure_time", sfDate);
        }
        if (StringUtils.isNotBlank(efDate)) {
            queryWrapper.le("fina_sure_time", efDate + " 23:59:59");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

        queryWrapper.inSql("id", " SELECT a.order_id  FROM  t_flower_preinfo a LEFT JOIN  flower_storehouse b on  a.storehouse = b.code   LEFT JOIN flower_storehouse_detail c on b.id = c.mainid WHERE personid = '" + sysUser.getId() + "'");
        QueryGenerator.installAuthMplus(queryWrapper, FlowerPre.class);
        Page<FlowerPre> page = new Page<FlowerPre>(pageNo, pageSize);
        queryWrapper.orderByDesc("no");
        queryWrapper.orderByDesc("create_time");
        IPage<FlowerPre> pageList = flowerPreService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param flowerPrePage
     * @return
     */
    @AutoLog(value = "销售确认单主表-添加")
    @ApiOperation(value = "销售确认单主表-添加", notes = "销售确认单主表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody FlowerPrePage flowerPrePage) throws IOException {
        synchronized (flowerPrePage) {
            FlowerPre flowerPre = new FlowerPre();
            BeanUtils.copyProperties(flowerPrePage, flowerPre);
            flowerPreService.saveMain(flowerPre, flowerPrePage.getFlowerPreinfoList(), flowerPrePage.getFlowerPreinfoHsList());
        }
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param flowerPrePage
     * @return
     */
    @AutoLog(value = "销售确认单主表-编辑")
    @ApiOperation(value = "销售确认单主表-编辑", notes = "销售确认单主表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody FlowerPrePage flowerPrePage) throws IOException {
        FlowerPre flowerPreEntity = flowerPreService.getById(flowerPrePage.getId());
        if (flowerPreEntity == null) {
            return Result.error("未找到对应数据");
        }
        if (flowerPreEntity.getState().compareTo(0) != 0) {
            return Result.error("草稿状态才能进行编辑");
        }
        String sealSureUser = flowerPrePage.getSealSureUser();
        if (StringUtils.isNotBlank(sealSureUser)) {
            return Result.error("已确认，不能进行编辑!请先撤销确认");
        }
        boolean accountState = settleAccountsService.getAccountState(flowerPrePage.getPeriod());
        if (!accountState) {
            throw new RuntimeException("已结账的单据不可编辑！");
        }
        synchronized (flowerPrePage.getId()) {
            FlowerPre flowerPre = new FlowerPre();
            BeanUtils.copyProperties(flowerPrePage, flowerPre);
            //自动计算合计
            BigDecimal snum = BigDecimal.ZERO;
            BigDecimal sumTotalprice = new BigDecimal(0);
            for (FlowerPreinfo flowerPreinfo : flowerPrePage.getFlowerPreinfoList()) {
                BigDecimal snumber = flowerPreinfo.getNumber();
                if (snumber == null) {
                    snumber = BigDecimal.ZERO;
                }
                snum = snum.add(snumber);
                BigDecimal totalprice = flowerPreinfo.getTotalprice();
                if (totalprice == null) {
                    totalprice = new BigDecimal(0);
                }
                sumTotalprice = sumTotalprice.add(totalprice.setScale(2, RoundingMode.HALF_UP));
            }
            flowerPre.setNumber(snum);
            flowerPre.setToalprice(sumTotalprice);
            flowerPreService.updateMain(flowerPre, flowerPrePage.getFlowerPreinfoList(), flowerPrePage.getFlowerPreinfoHsList());
        }
        return Result.ok("编辑成功!");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售确认单主表-通过id删除")
    @ApiOperation(value = "销售确认单主表-通过id删除", notes = "销售确认单主表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) throws IOException {
        FlowerPre flowerPre = flowerPreService.getById(id);
        if (StringUtils.isNotBlank(flowerPre.getFinaSureUser())) {
            return Result.error("财务已确认，不能删除");
        }
        flowerPreService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "销售确认单主表-批量删除")
    @ApiOperation(value = "销售确认单主表-批量删除", notes = "销售确认单主表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) throws IOException {
        Collection<FlowerPre> flowerPres = flowerPreService.listByIds(Arrays.asList(ids.split(",")));
        for (FlowerPre flowerPre : flowerPres) {
            if (StringUtils.isNotBlank(flowerPre.getFinaSureUser())) {
                throw new RuntimeException("财务已确认，不能删除");
            }
            if (flowerPre.getState() != 0) {
                throw new RuntimeException(flowerPre.getNo() + "草稿状态才能删除");
            }
            flowerPre.setState(-2);
        }
        flowerPreService.updateBatchById(flowerPres);
//        this.flowerPreService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售确认单主表-通过id查询")
    @ApiOperation(value = "销售确认单主表-通过id查询", notes = "销售确认单主表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        FlowerPre flowerPre = flowerPreService.getById(id);
        if (flowerPre == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(flowerPre);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售确认单子表通过主表ID查询")
    @ApiOperation(value = "销售确认单子表主表ID查询", notes = "销售确认单子表-通主表ID查询")
    @GetMapping(value = "/queryFlowerPreinfoByMainId")
    public Result<?> queryFlowerPreinfoListByMainId(@RequestParam(name = "id", required = true) String id,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        Page<FlowerPreinfo> page = new Page<FlowerPreinfo>(pageNo, pageSize);
        LambdaQueryWrapper<FlowerPreinfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FlowerPreinfo::getOrderId, id);
        IPage<FlowerPreinfo> flowerPreinfoList = flowerPreinfoService.page(page, lambdaQueryWrapper);
        return Result.ok(flowerPreinfoList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "销售确认单子表主表ID查询", notes = "销售确认单子表-通主表ID查询")
    @GetMapping(value = "/queryFlowerPreinfoByMainId2")
    public Result<?> queryFlowerPreinfoListByMainId2(@RequestParam(name = "id", required = true) String id,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        Page<FlowerPreinfoHs> page = new Page<FlowerPreinfoHs>(pageNo, pageSize);
        LambdaQueryWrapper<FlowerPreinfoHs> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FlowerPreinfoHs::getOrderId, id);
        IPage<FlowerPreinfoHs> flowerPreinfoList = flowerPreinfoHsService.page(page, lambdaQueryWrapper);
        return Result.ok(flowerPreinfoList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param flowerPre
     */
    @RequestMapping(value = "/exportXls")
    @PermissionData(pageComponent = "flower/FlowerPreList")
    @ApiOperation(value = "全部导出-按销售确认时间段导出", notes = "全部导出-按销售确认时间段导出")
    public ModelAndView exportXls(HttpServletRequest request, FlowerPre flowerPre,
                                  @RequestParam(name = "isSure", defaultValue = "") String isSure,
                                  @RequestParam(value = "sDate", defaultValue = "") String sDate,
                                  @RequestParam(value = "eDate", defaultValue = "") String eDate,
                                  @RequestParam(value = "sfDate", defaultValue = "") String sfDate,
                                  @RequestParam(value = "efDate", defaultValue = "") String efDate) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<FlowerPre> queryWrapper = QueryGenerator.initQueryWrapper(flowerPre, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        queryWrapper.orderByAsc("stock_out_time");
        queryWrapper.orderByAsc("seal_sure_time");
        queryWrapper.orderByAsc("create_time");
        if (StringUtils.isNotBlank(flowerPre.getSealSureUser())) {
            queryWrapper.eq("seal_sure_user", flowerPre.getSealSureUser());
        }
        if (StringUtils.isNotBlank(flowerPre.getFinaSureUser())) {
            queryWrapper.eq("fina_sure_user", flowerPre.getFinaSureUser());
        }
        if (StringUtils.isNotBlank(isSure)) {
            if ("1".equals(isSure)) {
                queryWrapper.isNotNull("fina_sure_user");
                queryWrapper.ne("fina_sure_user", "");
            } else if ("2".equals(isSure)) {
                queryWrapper.and(wrapper -> wrapper.or().isNull("fina_sure_user").or().eq("fina_sure_user", ""));
            }
        }
        if (StringUtils.isNotBlank(flowerPre.getNo())) {
            queryWrapper.like("no", flowerPre.getNo());
        }
        if (flowerPre.getState() != null) {
            queryWrapper.eq("state", flowerPre.getState());
        }

        if (StringUtils.isNotBlank(sDate)) {
            queryWrapper.ge("seal_sure_time", sDate);
        }
        if (StringUtils.isNotBlank(eDate)) {
            queryWrapper.le("seal_sure_time", eDate + " 23:59:59");
        }
        if (StringUtils.isNotBlank(sfDate)) {
            queryWrapper.ge("fina_sure_time", sfDate);
        }
        if (StringUtils.isNotBlank(efDate)) {
            queryWrapper.le("fina_sure_time", efDate + " 23:59:59");
        }
//        queryWrapper.exists("select 1 from t_flower_preinfo a, flower_storehouse b , flower_storehouse_detail c " +
//                "where b.id = c.mainid   and a.cost = b.cost and  a.order_id=t_flower_pre.id " +
//                "and personid = '" + sysUser.getId() + "'");
        queryWrapper.inSql("id", " SELECT a.order_id  FROM  t_flower_preinfo a LEFT JOIN  flower_storehouse b on  a.storehouse = b.code   LEFT JOIN flower_storehouse_detail c on b.id = c.mainid WHERE personid = '" + sysUser.getId() + "'");
        QueryGenerator.installAuthMplus(queryWrapper, FlowerPre.class);
        //Step.2 获取导出数据
        List<FlowerPre> queryList = flowerPreService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<FlowerPre> flowerPreList = new ArrayList<FlowerPre>();
        if (oConvertUtils.isEmpty(selections)) {
            flowerPreList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            flowerPreList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<FlowerPrePage> pageList = new ArrayList<FlowerPrePage>();
        for (FlowerPre main : flowerPreList) {
            FlowerPrePage vo = new FlowerPrePage();
            BeanUtils.copyProperties(main, vo);
            List<FlowerPreinfo> flowerPreinfoList = flowerPreinfoService.selectByMainId(main.getId());
            vo.setFlowerPreinfoList(flowerPreinfoList);

            List<FlowerPreinfoHs> flowerPreinfoLisths = flowerPreinfoHsService.selectByMainId(main.getId());
            vo.setFlowerPreinfoHsList(flowerPreinfoLisths);

            pageList.add(vo);

        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "销售确认单主表列表");
        mv.addObject(NormalExcelConstants.CLASS, FlowerPrePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("销售确认单主表数据", "导出人:" + sysUser.getRealname(), "销售确认单主表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }


    /**
     * 导出excel结算单
     * 需要和售后单做~~~~计算
     *
     * @param request
     * @param flowerOutorderPage
     * @return
     */
    @RequestMapping(value = "/exportXlsForAccont")
    public ModelAndView exportXlsForAccont(HttpServletRequest request, FlowerPre flowerOutorderPage) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
//        TemplateExportParams params = new TemplateExportParams("C:\\Users\\Administrator\\Desktop\\muban.xlsx");
        if (StringUtils.isBlank(tempPreExcelOrder)) {
            throw new RuntimeException("还未配置导出模板，请联系管理员配置导出模板");
        }
        TemplateExportParams params = null;
        try {
            params = new TemplateExportParams(tempPreExcelOrder);
        } catch (Exception e) {
            throw new RuntimeException("还未配置导出模板，请联系管理员配置导出模板");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderNo", flowerOutorderPage.getNo());
        map.put("outorderPreNo", flowerOutorderPage.getOutorderPreNo());
        String user = flowerOutorderPage.getStockOutUser();
        if (StringUtils.isBlank(user)) {
            user = "";
        }
        map.put("user", user);
        String channel = flowerOutorderPage.getChannel();
        if (StringUtils.isBlank(channel)) {
            channel = "";
        }
        map.put("channel", channel);
        String accountno = flowerOutorderPage.getAccountno();
        if (StringUtils.isBlank(accountno)) {
            accountno = "";
        }
        map.put("accountno", accountno);
        map.put("address", flowerOutorderPage.getAddress());
        Date createTime = flowerOutorderPage.getCreateTime();

        map.put("createTime", simpleDateFormat.format(createTime));//出库时间

        Date finaSureTime = flowerOutorderPage.getFinaSureTime();
        map.put("finaSureTime", simpleDateFormat.format(finaSureTime));//出库时间
        String stockOutUser = flowerOutorderPage.getSealSureUser();
        if (StringUtils.isBlank(stockOutUser)) {
            stockOutUser = "";
        }
        map.put("stockOutUser", stockOutUser);//经办人
        map.put("finaSureUser", flowerOutorderPage.getFinaSureUser());//财务确认人

        List<FlowerPreinfo> flowerPreinfoList = flowerPreinfoService.selectByMainId(flowerOutorderPage.getId());
        List<FlowerPreinfoHs> flowerPreinfoHsList = flowerPreinfoHsService.selectByMainId(flowerOutorderPage.getId());
        if (flowerPreinfoList.size() == 0) {
            throw new RuntimeException("没有出库详情不能生成出库单");
        }
        Map<String, String> costNames = CommonUtil.getCostNames();
        Map<String, String> houseNames = CommonUtil.getHouseNames();
        BigDecimal countPrice = new BigDecimal(0);
        BigDecimal countNum =  new BigDecimal(0);
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        for (FlowerPreinfo flowerPreinfo : flowerPreinfoList) {
            Map<String, Object> lm = new HashMap<String, Object>();
            lm.put("storehouse", houseNames.get(flowerPreinfo.getStorehouse()));
            lm.put("cost", costNames.get(flowerPreinfo.getCost()));
            lm.put("variety", flowerPreinfo.getVariety());
            lm.put("packingSpecifications", flowerPreinfo.getPackingSpecifications());
            lm.put("flowerPoleLength", flowerPreinfo.getFlowerPoleLength());
            lm.put("number", flowerPreinfo.getNumber());
            countNum = countNum.add(flowerPreinfo.getNumber());
            lm.put("price", flowerPreinfo.getPrice());
            lm.put("totalprice", flowerPreinfo.getTotalprice());
            countPrice = countPrice.add(flowerPreinfo.getTotalprice());
            listMap.add(lm);
        }
        if (flowerPreinfoList.size() == 1) {
            Map<String, Object> lm = new HashMap<String, Object>();
            listMap.add(lm);
        }
        BigDecimal countPriceHs = new BigDecimal(0);
        BigDecimal countNumHs = new BigDecimal(0);
        List<Map<String, Object>> listMapHs = new ArrayList<Map<String, Object>>();
        for (FlowerPreinfoHs flowerPreinfo : flowerPreinfoHsList) {
            Map<String, Object> lm = new HashMap<String, Object>();
            lm.put("storehouse", houseNames.get(flowerPreinfo.getStorehouse()));
            lm.put("cost", costNames.get(flowerPreinfo.getCost()));
            lm.put("variety", flowerPreinfo.getVariety());
            lm.put("packingSpecifications", flowerPreinfo.getPackingSpecifications());
            lm.put("flowerPoleLength", flowerPreinfo.getFlowerPoleLength());
            lm.put("number", flowerPreinfo.getNumber());
            countNumHs = countNumHs.add( flowerPreinfo.getNumber());
            lm.put("price", flowerPreinfo.getPrice());
            lm.put("totalprice", flowerPreinfo.getTotalprice());
            countPriceHs = countPriceHs.add(flowerPreinfo.getTotalprice());
            listMapHs.add(lm);
        }
        if (flowerPreinfoHsList.size() == 1) {
            Map<String, Object> lm = new HashMap<String, Object>();
            listMapHs.add(lm);
        }
        map.put("countPrice", countPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
        map.put("countNum", String.valueOf(countNum));
        map.put("maplist", listMap);
        map.put("countPriceHs", countPriceHs.setScale(2, BigDecimal.ROUND_HALF_UP));
        map.put("countNumHs", String.valueOf(countNumHs));
        map.put("maplistHs", listMapHs);
        ModelAndView mv2 = new ModelAndView(new JeecgTemplateExcelView());
        mv2.addObject(TemplateExcelConstants.PARAMS, params);
        mv2.addObject(TemplateExcelConstants.MAP_DATA, map);
        return mv2;
    }


    /**
     * @return org.jeecg.common.api.vo.Result<?>
     * @descriptionauthor 基地负责人审批
     * @author gf
     * 2022-12-22 13:40
     * [id]
     */
    @AutoLog(value = "基地负责人审批")
    @ApiOperation(value = "===基地负责人审批", notes = "====基地负责人审批")
    @GetMapping(value = "/sealSureOut")
    public Result<?> sealSureOut(@RequestParam(name = "id", required = true) String id) {
        int rest = 0;
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        synchronized (id) {
            //1、修改预出库主表财务确认人
//            状态（0草稿，1基地负责人审批，2运管备案，3财务确认，）
            FlowerPre flowerPreOld = flowerPreService.getById(id);
            if (flowerPreOld != null && StringUtils.isNotBlank(flowerPreOld.getSealSureUser())) {
                throw new RuntimeException("已经确认过了");
            }
            if (flowerPreOld.getState().compareTo(1) == 0) {
                throw new RuntimeException("已经确认过了");
            }
            if (flowerPreOld.getState().compareTo(0) != 0) {
                throw new RuntimeException("还不可以基地负责人审批");
            }
            FlowerPre flowerPre = new FlowerPre();
            flowerPre.setId(id);
            flowerPre.setSealSureUser(sysUser.getRealname());
            flowerPre.setSealSureTime(new Date());
//            flowerPre.setPipSure(flowerPreOld.getPipSure());
//            flowerPre.setPipSureTime(flowerPreOld.getPipSureTime());
//            flowerPre.setFinaSureUser(sysUser.getRealname());
//            flowerPre.setFinaSureTime(new Date());
            flowerPre.setState(1);
            flowerPreService.updateById(flowerPre);

        }
        return Result.ok("基地负责人审批成功！");
    }

    /**
     * 财务撤销
     *
     * @param id
     * @return
     */
    @AutoLog(value = "基地负责人审批")
    @ApiOperation(value = "基地负责人审批", notes = "基地负责人审批")
    @GetMapping(value = "/sealSureOutBack")
    public Result<?> sealSureOutBack(@RequestParam(name = "id", required = true) String id) {
        int rest = 0;
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        synchronized (id) {
            //1、修改预出库主表财务确认人
            FlowerPre flowerPreOld = flowerPreService.getById(id);
            if (flowerPreOld == null || StringUtils.isBlank(flowerPreOld.getSealSureUser())) {
                throw new RuntimeException("基地负责人还未确认");
            }
            if (flowerPreOld.getState().compareTo(1) != 0) {
                throw new RuntimeException("不能再撤销确认");
            }
            if (!sysUser.getRealname().equals(flowerPreOld.getSealSureUser()) && !"admin".equals(sysUser.getUsername())) {
                throw new RuntimeException("只能撤销自己确认的单据");
            }
            FlowerPre flowerPre = new FlowerPre();
            flowerPre.setId(id);
            flowerPre.setSealSureUser("");
            flowerPre.setSealSureTime(null);
//            flowerPre.setPipSure(flowerPreOld.getPipSure());
//            flowerPre.setPipSureTime(flowerPreOld.getPipSureTime());
//            flowerPre.setFinaSureUser("");
//            flowerPre.setFinaSureTime(null);
            flowerPre.setState(0);
            flowerPreService.updateById(flowerPre);
        }
        return Result.ok("撤销基地负责人审批成功！");
    }

    /**
     * @return org.jeecg.common.api.vo.Result<?>
     * @descriptionauthor 运管备案
     * @author gf
     * 2022-12-22 13:40
     * [id]
     */
    @AutoLog(value = "运管备案")
    @ApiOperation(value = "===运管备案", notes = "====运管备案")
    @GetMapping(value = "/pipSureOut")
    public Result<?> pipSureOut(@RequestParam(name = "id", required = true) String id) {
        int rest = 0;
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        synchronized (id) {
            //1、修改预出库主表财务确认人
//            状态（0草稿，1基地负责人审批，2运管备案，3财务确认，）
            FlowerPre flowerPreOld = flowerPreService.getById(id);
            if (flowerPreOld != null && StringUtils.isNotBlank(flowerPreOld.getPipSure())) {
                throw new RuntimeException("已经确认过了");
            }
            if (flowerPreOld.getState().compareTo(2) == 0) {
                throw new RuntimeException("已经确认过了");
            }
            if (flowerPreOld.getState().compareTo(1) != 0) {
                throw new RuntimeException("还不可以运管备案");
            }
            FlowerPre flowerPre = new FlowerPre();
            flowerPre.setId(id);
            flowerPre.setSealSureUser(flowerPreOld.getSealSureUser());
            flowerPre.setSealSureTime(flowerPreOld.getSealSureTime());
            flowerPre.setPipSure(sysUser.getRealname());
            flowerPre.setPipSureTime(new Date());
            flowerPre.setState(2);
//            flowerPre.setFinaSureUser(sysUser.getRealname());
//            flowerPre.setFinaSureTime(new Date());
            flowerPreService.updateById(flowerPre);

        }
        return Result.ok("运管备案成功！");
    }

    /**
     * 财务撤销
     *
     * @param id
     * @return
     */
    @AutoLog(value = "运管备案-撤销")
    @ApiOperation(value = "运管备案-撤销", notes = "运管备案-撤销")
    @GetMapping(value = "/pipSureOutBack")
    public Result<?> pipSureOutBack(@RequestParam(name = "id", required = true) String id) {
        int rest = 0;
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        synchronized (id) {
            //1、修改预出库主表财务确认人
            FlowerPre flowerPreOld = flowerPreService.getById(id);
            if (flowerPreOld == null || StringUtils.isBlank(flowerPreOld.getPipSure())) {
                throw new RuntimeException("基地负责人还未确认");
            }
            if (flowerPreOld.getState().compareTo(2) != 0) {
                throw new RuntimeException("不能再撤销确认");
            }
            if (!sysUser.getRealname().equals(flowerPreOld.getPipSure()) && !"admin".equals(sysUser.getUsername())) {
                throw new RuntimeException("只能撤销自己确认的单据");
            }
            FlowerPre flowerPre = new FlowerPre();
            flowerPre.setId(id);
            flowerPre.setSealSureUser(flowerPreOld.getSealSureUser());
            flowerPre.setSealSureTime(flowerPreOld.getSealSureTime());
            flowerPre.setPipSure("");
            flowerPre.setPipSureTime(null);
            flowerPre.setState(1);

//            flowerPre.setFinaSureUser(sysUser.getRealname());
//            flowerPre.setFinaSureTime(new Date());
            flowerPreService.updateById(flowerPre);
        }
        return Result.ok("撤销成功！");
    }

    /**
     * @return org.jeecg.common.api.vo.Result<?>
     * @descriptionauthor 财务确认
     * @author gf
     * 2022-12-22 13:40
     * [id]
     */
    @AutoLog(value = "财务确认")
    @ApiOperation(value = "财务确认===财务确认", notes = "财务确认====财务确认")
    @GetMapping(value = "/finSureOut")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> finSureOut(@RequestParam(name = "id", required = true) String id,
                                @RequestParam(name = "receipt", required = true) String receipt,
                                @RequestParam(name = "getMoney", required = true) BigDecimal getMoney) throws IOException {
        synchronized (CommonUtil.SUBTAGPREINFOKEY) {
            //1、修改预出库主表财务确认人
//            状态（0草稿，1基地负责人审批，2运管备案，3财务确认，）
            FlowerPre flowerPreOld = flowerPreService.getById(id);
            flowerPreOld.setReceipt( receipt );
            flowerPreOld.setGetMoney( getMoney );
            //扣减预出库的台账库存
            flowerPreService.finSureOut(flowerPreOld);
        }
        return Result.ok("财务确认成功！");
    }

    /**
     * 财务撤销
     *
     * @param id
     * @return
     */
    @AutoLog(value = "财务撤销")
    @ApiOperation(value = "财务撤销", notes = "财务撤销")
    @GetMapping(value = "/backOut")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> backOut(@RequestParam(name = "id", required = true) String id) throws IOException {
        synchronized (CommonUtil.SUBTAGPREINFOKEY) {
            FlowerPre flowerPreOld = flowerPreService.getById(id);
            flowerPreService.finSureOutBack(flowerPreOld);
//            //1、修改预出库主表财务确认人
//
//            if (flowerPreOld == null || StringUtils.isBlank(flowerPreOld.getFinaSureUser())) {
//                throw new RuntimeException("财务还未确认");
//            }
//            if (flowerPreOld.getState().compareTo(3) != 0) {
//                throw new RuntimeException("不能再撤销确认");
//            }
//            if (!sysUser.getRealname().equals(flowerPreOld.getFinaSureUser())) {
//                throw new RuntimeException("只能撤销自己确认的单据");
//            }
//            FlowerPre flowerPre = new FlowerPre();
//            flowerPre.setId(id);
//            flowerPre.setSealSureUser(flowerPreOld.getSealSureUser());
//            flowerPre.setSealSureTime(flowerPreOld.getSealSureTime());
//            flowerPre.setPipSure(flowerPreOld.getPipSure());
//            flowerPre.setPipSureTime(flowerPreOld.getPipSureTime());
//            flowerPre.setFinaSureUser("");
//            flowerPre.setFinaSureTime(null);
//            flowerPre.setState(2);
//            flowerPreService.updateById(flowerPre);
//
//            //扣减预出库的台账库存
//            flowerPreService.subTagPreInfoBack(flowerPreOld);
        }
        return Result.ok("撤销成功！");
    }

}
